package com.demo.function.graylog;

import biz.paluch.logging.gelf.intern.GelfMessage;
import biz.paluch.logging.gelf.logback.GelfLogbackAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;

/**
 * GelfLogbackAppender扩展类，includeFullMdc=true将skywalking的traceId添加graylog自定义字段上。
 * 相当于配置additionalFields
 * @author cyj
 **/
public class GelfLogbackAppenderExtend extends GelfLogbackAppender {

    @Override
    protected void append(ILoggingEvent event) {
        if (event == null) {
            return;
        }

        try {
            GelfMessage message = createGelfMessage(event);

            if (isIncludeFullMdc()) {
                // 可以通过skywalking手动追踪API来获取，因为通过MDC不能获取到traceId（tid）
                String traceId = TraceContext.traceId();
                message.addField("TID", traceId);
            }

            if (!message.isValid()) {
                reportError("GELF Message is invalid: " + message.toJson(), null);
                return;
            }

            if (null == gelfSender || !gelfSender.sendMessage(message)) {
                reportError("Could not send GELF message", null);
            }
        } catch (Exception e) {
            reportError("Could not send GELF message: " + e.getMessage(), e);
        }
    }
}
